Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java Functional Interfaces

  • Java Functional Interfaces are special types of interfaces introduced in Java 8 that provide a way to use functional programming concepts in Java. Functional interfaces are interfaces that have exactly one abstract method and are annotated with the @FunctionalInterface annotation. It is also referred to as "Single Abstract Method (SAM) interfaces".

  • Functional interfaces can be used to represent functions, predicates, consumers, and suppliers as objects. It enable the use of lambda expressions, which provide a easy way to define behavior in a functional style.
Table Of Content

  • Java Functional Interfaces
  • functional interface with anonymous inner class
  • functional interface using lambda expressions
  • functional interface using @FunctionalInterface Annotation
  • Java Predefined Functional Interfaces





  • Lambda expressions are anonymous functions that can be used in place of an interface implementation when an interface is expected.
  • Functional interfaces eliminate the necessity of employing the "abstract" keyword, rendering it optional since the methods defined within the interface are inherently abstract. Remarkably, Lambda expressions can be referred to as functional interfaces' instances, accentuating their versatility and succinctness in code representation.

Java program of functional interface with anonymous inner class


// Java program to demonstrate functional interface

class Test {
    public static void main(String args[])
    {
        new Thread(new Runnable() {
            @Override public void run()
            {
                System.out.println("New Thread ");
            }
        }).start();
    }
}

Output:

New Thread  

Java program of functional interface using lambda expressions


class Test {
    public static void main(String args[])
    {  
        new Thread(() -> { // lambda expression  
            System.out.println("New Thread ");
        }).start();
    }
}




Output:

New Thread  

Java program of functional interface using @FunctionalInterface Annotation


To ensure that the functional interface can only have one abstract method, the @FunctionalInterface annotation is used. An "Unexpected @FunctionalInterface annotation" message is flagged by the compiler if there are multiple abstract methods present. It is not necessary to use this annotation, though.


@FunctionalInterface
interface Operation {
    int operate(int a, int b);
}

public class Calculator {
    public static void main(String[] args) {
        Operation add = (a, b) -> a + b;
        Operation subtract = (a, b) -> a - b;
        Operation multiply = (a, b) -> a * b;

        int result1 = calculate(5, 2, add);
        int result2 = calculate(5, 2, subtract);
        int result3 = calculate(5, 2, multiply);

        System.out.println(result1); // prints 7
        System.out.println(result2); // prints 3
        System.out.println(result3); // prints 10
    }

    public static int calculate(int a, int b, Operation op) {
        return op.operate(a, b);
    }
}

Output:

7
3
10 

In this example, we define a functional interface called Operation with a single method called operate that takes two integers and returns an integer. We use the @FunctionalInterface annotation to indicate that this interface is intended to be used as a functional interface.


We then define three instances of the Operation interface using lambda expressions for addition, subtraction, and multiplication. We pass these instances to the calculate method, which takes two integers and an instance of the Operation interface, and returns the result of applying the operation to the integers.


When we run the program, we get the results of calculating the sum, difference, and product of 5 and 2, using the different operations.





Java Predefined-Functional Interfaces


Java offers predefined functional interfaces that use lambda and method references to deal with functional programming. Additionally, you can create a unique functional interface. Here is a list of the functional interfaces found in the java.util.function package.


  • Consumer - It represents an operation that only takes a single argument of type T as input and produces no output.
    Consumer<String> printStr = s -> System.out.println(s);
    printStr.accept("Hello World!"); // Output: "Hello World!"
    

  • BiConsumer - Represents an operation that accepts two input arguments of types T and U and returns no result.
    BiConsumer<String, Integer> printInfo = (name, age) -> System.out.println(name + " is " + age + " years old.");
    printInfo.accept("John", 30); // Output: "John is 30 years old."
    



  • Supplier - Represents a supplier of results.
    Supplier<Integer> getRandomNumber = () -> (int) (Math.random() * 100);
    int num = getRandomNumber.get(); // Returns a random number between 0 and 100
    

  • Function - Represents a function that accepts one argument of type T and returns a result of type R.
    Function<String, Integer> getStrLength = s -> s.length();
    int length = getStrLength.apply("Hello"); // Returns 5
    

  • BiFunction - Represents a function that accepts two arguments of types T and U and returns a result of type R.
    BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
    int sum = add.apply(2, 3); // Returns 5
    

  • UnaryOperator - represents an operation that produces a result of type T from a single operand of type T.
    UnaryOperator<Integer> square = x -> a * a;
    int num = square.apply(5); // Returns 25
    



  • BinaryOperator - It represents a function that is applied to two operands of the same type to produce an operand-type-compatible result.
    BinaryOperator<Integer> add = (a, b) -> a + b;
    int sum = add.apply(2, 3); // Returns 5
    

  • Predicate - it represents a boolean-valued function that acts as a predicate with a single argument.
    Predicate<Integer> isEven = x -> x % 2 == 0;
    boolean result = isEven.test(4); // Returns true
    

  • BiPredicate - Represents a predicate (boolean-valued function) of two arguments.
    BiPredicate<Integer, Integer> isSumEven = (a, b) -> (a + b) % 2 == 0;
    boolean result = isSumEven.test(2, 3); // Returns true
    



  • ToIntFunction - Represents a function that accepts an argument of type T and produces an int-valued result.
    ToIntFunction<String> getStrLength = s -> s.length();
    int length = getStrLength.applyAsInt("Hello"); // Returns 5
    

  • ToLongFunction - it represents a function that accepts a T-type argument and outputs long-valued results.
    ToLongFunction<String> getStrHash = s -> s.hashCode();
    long hash = getStrHash.applyAsLong("Hello"); // Returns a hash value of the string
    

  • ToDoubleFunction - Represents a function that accepts an argument of type T and produces a double-valued result.
    ToDoubleFunction<String> getStrLength = s -> (double) s.length();
    double length = getStrLength.applyAsDouble("Hello"); // Returns 5.0
    



  • IntFunction - Represents a function that take an int-valued argument and produces a result of type R.
    IntFunction<String> getStrWithLength = length -> "The length of this string is " + length;
    String str = getStrWithLength.apply(10); // Returns "The length of this string is 10"
    

  • LongFunction - Represents a function that accepts a long-valued argument and produces a result of type R.
    LongFunction<String> getStrWithHash = hash -> "The hash value of this string is " + hash;
    String str = getStrWithHash.apply("Hello".hashCode()); // Returns "The hash value of this string is <hash_value>"
    

  • DoubleFunction - It represent a function that takes a double-valued argument and outputs an R-typed result.
    DoubleFunction<String> getStrWithSquare = x -> "The square of " + x + " is " + (x * x);
    String str = getStrWithSquare.apply(5.0); // Returns "The square of 5.0 is 25.0"
    



  • IntSupplier - Represents a supplier of int-valued results.
    IntSupplier getRandomNumber = () -> (int) (Math.random() * 100);
    int num = getRandomNumber.getAsInt(); // Returns a random number between 0 and 100
    

  • LongSupplier - Represents a supplier of long-valued results.
    LongSupplier getCurrentTime = () -> System.currentTimeMillis();
    long time = getCurrentTime.getAsLong(); // Returns the current time in milliseconds
    

  • DoubleSupplier - Represents a supplier of double-valued results.
    DoubleSupplier getRandomDouble = () -> Math.random();
    double num = getRandomDouble.getAsDouble(); // Returns a random double value between 0.0 and 1.0
    



  • IntPredicate - Represents a predicate (boolean-valued function) of one argument of type int.
    IntPredicate isEven = x -> x % 2 == 0;
    boolean result = isEven.test(4); // Returns true
    

  • LongPredicate - Represents a predicate (boolean-valued function) of one argument of type long.
    LongPredicate isPositive = x -> x > 0;
    boolean result = isPositive.test(10L); // Returns true
    



  • DoublePredicate - Represents a predicate (boolean-valued function) of one argument of type double.
    DoublePredicate isGreaterThanOne = x -> x > 1.0;
    boolean result = isGreaterThanOne.test(2.0); // Returns true
    
Java 8 Stream Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.